<template>
  <el-form ref='form' :model="form" :rules="rules" :hide-required-asterisk="true" label-position="left" style="margin:0 20px;">
    <el-form-item :label="$t('地址组名称')" :label-width="formLabelWidth" prop="name">
      <el-input v-emoji size='small' v-model="form.name" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item :label="$t('描述')" :label-width="formLabelWidth">
      <el-input v-emoji type="textarea" @keydown.native="handleKeyCode($event)" :autosize="{ minRows: 2, maxRows: 4}" :placeholder="$t('请输入内容')" v-model="form.describe">
      </el-input>
    </el-form-item>

    <!--    添加对象页面-->
    <div>
      <el-button type="success" size='small' @click="add_addr()">{{$t('添加对象')}}</el-button>
      <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加对象')" :v-if="dialogAddrFormVisible" :visible.sync="dialogAddrFormVisible" width="600px" top="10vh" append-to-body>
        <el-table size='mini' :data="addr_list" tooltip-effect="dark" header-align="center" max-height="500px" align="center" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column align='center' type="selection" width="55">
          </el-table-column>
          <el-table-column align='center' prop="name" :label="$t('名称')">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.name" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column align='center' prop="ip_type" :label="$t('类型')" :formatter="ip_type">
          </el-table-column>
          <el-table-column align='center' prop="ip" label="IP/MAC">
            <template slot-scope="scope">
              <tooltip :html="ipmacTooltip(scope.row)" :content="ipmacTooltip(scope.row)" class="wid190" :refName="ipmacTooltip(scope.row)">
              </tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="add_addr_submit">{{$t('确定')}}</el-button>
          <el-button @click="dialogAddrFormVisible = false">{{$t('取消')}}</el-button>
        </div>
      </el-dialog>

      <el-table size='mini' :data="tableData" stripe border style="width: 100%;margin-top:10px;">
        <el-table-column align='center' prop='name' :label="$t('名称')">
          <template slot-scope="scope">
            <tooltip :html="scope.row.name" :content="scope.row.name" class="wid190" :refName="scope.row.name">
            </tooltip>
          </template>
        </el-table-column>
        <el-table-column align='center' fixed="right" :label="$t('操作')" width="120">
          <template slot-scope="scope">
            <el-button @click.native.prevent="deleteRow(scope.$index, tableData)" type="danger" plain size="mini">
              {{$t('删除')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-form>
</template>

<script>
import { getAddrArray } from '@/api/list/addr'
export default {
  name: 'AddrGroupTools',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入对象名称')))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '',
        describe: ''
      },
      addr_list: [],
      addrSelection: [],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        ex_len: [
          { required: true, message: this.$t('前缀长度不能为空') },
          { type: 'number', message: this.$t('前缀长度必须为数字值') }
        ]
      },
      tableData: [
      ],
      formLabelWidth: '140px',
      dialogFormVisible: false,
      dialogAddrFormVisible: false,
      visible: false,
      add_ip_str: ''
    }
  },
  watch: {
    'dialogAddrFormVisible': {
      handler (newVal) {
        if (newVal === true) {
          this.addr_list = []
          this.addrSelection = []
          getAddrArray().then(response => {
            if (response.status === 0) {
              this.addr_list = response.info
              this.addr_list.forEach((item, index, array) => {
                if (item.sys === 1) {
                  delete this.addr_list[index]
                }
              })
            }
          })
        }
      },
      immediate: true
    },
    'form.describe': {
      handler (newVal) {
        this.form.describe = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    sendCommand () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.tableData && this.tableData.length > 0) {
            let formData = JSON.parse(JSON.stringify(this.form))
            let member = []
            for (let item of this.tableData) {
              member.push(item.name)
            }
            formData.member = member.join(',')

            this.$emit('childForm', formData, this.form.name)
          } else {
            this.$messages.error(this.$t('对象不能为空'))
          }
        }
      })
    },
    ipmacTooltip (row) {
      if (row.ip_type === 7) {
        return row.mac
      } else {
        return row.ip.join(',')
      }
    },
    closeDialog () {
      this.dialogFormVisible = false
      this.form = {
        name: '',
        describe: ''
      }
      this.tableData = []
      this.$refs.form.resetFields()
    },
    handleSelectionChange (val) {
      this.addrSelection = val
    },
    add_addr_submit () {
      this.addrSelection.forEach(values => {
        if (this.tableData.findIndex(item => item.name === values.name) === -1) {
          this.tableData.push({ 'name': values.name })
        }
      })
      this.dialogAddrFormVisible = false
    },
    ip_type (row) {
      switch (row.ip_type) {
        case 1:
          return 'IPv4'
        case 2:
          return 'IPv4-NET'
        case 3:
          return 'IPv4-RANGE'
        case 4:
          return 'IPv6'
        case 5:
          return 'IPv6-NET'
        case 7:
          return 'MAC'
        default:
          return this.$t('其他')
      }
    },
    add () {
      this.dialogFormVisible = true
    },
    add_addr () {
      this.dialogAddrFormVisible = true
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>

<style scoped>
.tools_box {
  text-align: left;
}
.circle {
  padding: 5px;
}
</style>
